<?php
declare (strict_types = 1);
namespace app\api\controller;


use app\models\Zdb;
use app\models\Cpb;
use app\models\MYtestliu;
use app\models\MYtestgu;
use think\facade\Cache;
use think\facade\Db;
use app\api\validate\Destination;

class SellTickets
{
	/**
    * 选择站点
    * [getSites description]
    * @Author zyq
    * DateTime 2019-11-26T21:09:17+0800
    * @return [type] [description]
    * POST提交pybm
    */
    public function getSites()
    {
        // 获取站点拼音编码
        $data=$_POST['pybm'];
        
        // 验证拼音编码格式是否符合要求，不符合弹出错误信息
        try {
            validate(Destination::class)->check([
                'pybm'  => $data
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
           return json($e->getError());
        }
        
        $sites =Zdb::where('U_zdb.pybm',$data)
            ->field('U_zdb.mdzh,U_zdb.mdzm')
            ->select();

        return json($sites);
    }



    /**
     * 选择线路（流水）
     * 使用参数区分返回的是json数据还是数组数据,returntype(返回方式)
     * [getLineliu description]
     * @Author zyq
     * DateTime 2019-11-27T09:21:21+0800
     * @return [type] [description]
    * POST提交mdzh，returntype
    */
    public function getLineliu(){

       $data=$_POST['mdzh'];

       $listliu=Mytestliu::where('Mytestliu.mdzh',$data)
                    ->field('mdzm,mdzh,bclx,xlbh,xlmc,jpk,zdpj+tbpj as pj,tbpj')
                    ->select();
        if ($_POST['returntype']=='json') {

            return  json($listliu);

        }elseif ($_POST['returntype']=='array') {

            return $listliu;

        }else{

            return json([
                'code' => '1000007',
                'msg' => '请求方式错误请重试',
            ]);
        } 
    }

    /**
     * 选择线路（固定）选择线路时 查询缓存中剩余座位数组，并且算出还有多少剩余座位
    * POST提交mdzh，returntype
    */
    public function getLinegu(){
        
        $data=$_POST['mdzh'];
        
        $listgu=Mytestgu::where('Mytestgu.mdzh',$data)
                    ->field('mdzm,mdzh,bclx,bbkh,cpzh,zwgs,date_format(fcsj,"%H:%i:%s") as dtfcsj,fcsj,xlbh,bcbh,xlmc,jpk,zdpj+tbpj as pj,tbpj')
                    ->select();

        //将座位个数生成数组存到缓存中
        // for ($i=1; $i <=5 ; $i++) { 
        //     $arr1[$i-1]=$i;
        // }
        // foreach ($listgu as $key => $value) {
        //     # code...
        //     Cache::store('redis')->set($value['bbkh'].'_'.$value['fcsj'],$arr1);
        // }
        foreach ($listgu as $key => $value) {
            # code...
            $arr=Cache::store('redis')->get($value['bbkh'].'_'.$value['fcsj']);
             if(count($arr)==0){                //当座位个数为0时，不显示此条数据
                unset($listgu[$key]);
            }else{
             $value['syzw']=count($arr); 
            }
            
        }
        if ($_POST['returntype']=='json') {

            return  json($listgu);

        }elseif ($_POST['returntype']=='array') {

            return $listgu;

        }else{

            return json([
                'code' => '1000007',
                'msg' => '请求方式错误请重试',
            ]);
        }

    }



    /**
     * 售票，分为流水售票和固定售票
     * @Author zyq
     * DateTime 2019-12-06T20:08:10+0800
     * field('mdzm,mdzh,bclx,xlbh,xlmc,jpk,zdpj+tbpj as pj,tbpj')
     * POST提交bclx(班次类型)，xlbh(线路编号)，bbkh(报班卡号)，mdzh(目的站号)，returntype(请求方式)，cpbh(车票编号)，cplx(车票类型)，lkxm(乘客姓名)，sfzh(身份证号)，pj(票价，用来记录是否是半价票)
     */
    public function SellTickets(){

            $data=$_POST;
    
            if ($data['bclx']=="流水") {

                $list=$this->getLineliu();
                foreach ($list as $key => $value) {

                    if ($value['xlbh']==$data['xlbh']) {
                        $result=$value;
                        //需要进行票号的修改，判断票号是否大于终止票号，大于终止票号则加一，并重新写入数据库中
                        $ticket=[
                            'cpbh'     =>      '123456789' ,        //需要从前台传回车票编号，$data['cpbh'];   需修改
                            'mdcz'     =>      $result['mdzm'],
                            'spy'      =>      'sp30',             //获取当前账户的账户名称， 需修改
                            'pj'       =>      $result['pj'],
                            'rqsj'     =>      date("Y-m-d").' '.'9:00:00',
                            'zwh'      =>      '0',
                            'cplx'     =>      '全票',             //需要前台传入数据，需修改
                            'jpk'      =>      $result['jpk'],
                            'bbkh'     =>      '999',
                            'tbpj'     =>      $result['tbpj'],
                            'spsj'     =>      date("Y-m-d H-i-s"),
                            'xlbh'     =>      $result['xlbh'],
                            'mdzh'     =>      $result['mdzh'], 
                            'ssgs'     =>      '邯大三公司',        //写死
                            'bcbh'     =>      '流水',         
                            'lkxm'     =>      '张雨晴',           //身份证读取器上，读取
                            'sfzh'     =>      '12345678910'       //需要从前台获取
                        ];
                        $result= Db::table('U_cpb')->insert($ticket);

                        return $result;
                    }
                }

            }elseif ($data['bclx']=="固定") {
               
               Db::transaction(function () {
                $data=$_POST;
                $list=$this-> getLinegu();
                foreach ($list as $key => $value) {
                    
                   if ($value['bbkh']==$data['bbkh']) {
                       
                      $result=$value;
                       
                      //获取座位号，并将此座位号在缓存中删除
                        
                            $arr=Cache::store('redis')->get($value['bbkh'].'_'.$value['fcsj']);
                            $zwh=array_shift($arr);
                            Cache::store('redis')->set($value['bbkh'].'_'.$value['fcsj'],$arr);
                            //需要进行票号的修改，判断票号是否大于终止票号，大于终止票号则加一，并重新写入数据库中
                            $ticket=[
                                'cpbh'     =>      '131175410' ,        //需要从前台传回车票编号，$data['cpbh'];   需修改
                                'mdcz'     =>      $result['mdzm'],
                                'spy'      =>      'sp30',             //获取当前账户的账户名称， 需修改
                                'pj'       =>      $result['pj'],
                                'rqsj'     =>      $result['fcsj'],
                                'zwh'      =>      $zwh,
                                'cplx'     =>      '全票',             //需要前台传入数据，需修改
                                'jpk'      =>      $result['jpk'],
                                'bbkh'     =>      $result['bbkh'],
                                'tbpj'     =>      $result['tbpj'],
                                'spsj'     =>      date("Y-m-d H-i-s"),
                                'xlbh'     =>      $result['xlbh'],
                                'mdzh'     =>      $result['mdzh'], 
                                'ssgs'     =>      '邯大三公司',        //写死
                                'bcbh'     =>      $result['bcbh'],         
                                'lkxm'     =>      '张雨晴',           //身份证读取器上，读取  
                                'sfzh'     =>      '12345678910'       //需要从前台获取
                            ];
                            $result= Db::table('U_cpb')->insert($ticket);

                            return $ticket;
                      }  
                }
            });
        }
          
    }

    /**
     * 预售票线路查询
     * POST请求数据mdzh(目的站号)，fcsj(发车时间，预售日期)，returntype(请求方式),
     */
    public function getPresaleLine(){

        $data=$_POST;

        $listyu=Db::table('Mytestyu')->where([
            ['mdzh','=', $data['mdzh']],
            ['ysfcsj','like',$data['fcsj'].'%']
            ])
            ->field('mdzm,mdzh,bclx,ysbbkh,cpzh,zwgs,ysfcsj,xlbh,bcbh,xlmc,jpk,zdpj+tbpj as pj,tbpj')
            ->select(); 

        if(!count($listyu)){
            return json([
                'code' => '1000007',
                'msg' => '查询失败，没有找到该车辆',
            ]);
        }
        
        foreach ($listyu as $key => $value) {

             //判断键值是否存在，是否之前买过票       
            $result=Cache::store('redis')->exists($value['ysbbkh'].'_'.$value['ysfcsj']);

            if ($result) {    
              $arr=Cache::store('redis')->get($value['ysbbkh'].'_'.$value['ysfcsj']);
               if(count($arr)!=0){                //只显示座位个数不为0的数据
                    $value['syzw']=count($arr);  
                    $return[] = $value;
                }    
            }else{
                
                for ($i=1; $i<=$value['zwgs']; $i++) { 

                    $arr1[$i-1]=$i;               
                }
                Cache::store('redis')->set($value['ysbbkh'].'_'.$value['ysfcsj'],$arr1);
                $value['syzw']=count($arr1);
                $return[] = $value;            //将没有卖过票的数据写到数组中
            }       
        }
        if ($_POST['returntype']=='json') {

            return  json($return);

        }elseif ($_POST['returntype']=='array') {

            return $return;

        }else{

            return json([
                'code' => '1000007',
                'msg' => '请求方式错误请重试',
            ]);
        }
    }

    /**
     * 预售车票
     * POST请求数据mdzh(目的站号)，fcsj(发车时间，预售日期)，returntype(请求方式)，ysbbkh(预售报班卡号),cpbh(车票编号)，cplx(车票类型)，lkxm(乘客姓名)，sfzh(身份证号)，pj(票价)
     */
    public function SellPreTickets(){

        $data=$_POST;

        $list=$this-> getPresaleLine();

        foreach ($list as $key => $value) {
                   
            if ($value['ysbbkh']==$data['ysbbkh']) {
                       
                $result=$value;
                       
                //获取座位号，并将此座位号在缓存中删除
                            
                $arr=Cache::store('redis')->get($value['ysbbkh'].'_'.$value['ysfcsj']);
                $zwh=array_shift($arr);
                Cache::store('redis')->set($value['ysbbkh'].'_'.$value['ysfcsj'],$arr);
                //需要进行票号的修改，判断票号是否大于终止票号，大于终止票号则加一，并重新写入数据库中
                $ticket=[
                    'cpbh'     =>      '131175411' ,        //需要从前台传回车票编号，$data['cpbh'];   需修改
                    'mdcz'     =>      $result['mdzm'],
                    'spy'      =>      'sp30',             //获取当前账户的账户名称， 需修改
                    'pj'       =>      $result['pj'],      //需要获取
                    'rqsj'     =>      $result['ysfcsj'],
                    'zwh'      =>      $zwh,
                    'cplx'     =>      '全票',             //需要前台传入数据，需修改
                    'jpk'      =>      $result['jpk'],
                    'bbkh'     =>      $result['ysbbkh'],
                    'tbpj'     =>      $result['tbpj'],
                    'spsj'     =>      date("Y-m-d H-i-s"),
                    'xlbh'     =>      $result['xlbh'],
                    'mdzh'     =>      $result['mdzh'], 
                    'ssgs'     =>      '邯大三公司',        //写死
                    'bcbh'     =>      $result['bcbh'],         
                    'lkxm'     =>      '张雨晴',           //身份证读取器上，读取  
                    'sfzh'     =>      '12345678910',       //需要从前台获取
                    'yspbj'    =>      '1'
                ];
                $result= Db::table('U_cpb')->insert($ticket);

                return join($ticket);
            }  
        }
    }


    

    /**
     * 查询废除的车票是否存在
     * [getTicket description]
     * @Author zyq
     * DateTime 2019-11-27T09:43:11+0800
     * @return [type] [description]
     */
    public function getTicket(){

         $data=$_POST['cpbh'];
         
         // 固定写死，两套系统
         $ssgs='邯大三公司';

         $result=Cpb::where(['U_cpb.cpbh' => $data,
                     'U_cpb.cpzt' => '正常',
                     'U_cpb.sfjp' => '未检',
                     'U_cpb.ssgs' => $ssgs
                   ])->select();

         if (count($result)) {
             return $result;
         }else{
            return json([
                'code' => '1000007',
                'msg' => '查询失败，没有该票',
            ]);
         }
    }
    

       /**
    * 废票操作
    * @Author zyq
    * DateTime 2019-11-28T10:16:44+0800
    * @return [type] [description]
    */
    public function scrapTicket(){

        // 废票操作事务，报错回滚
        Db::transaction(function () {

            $data= $this->getTicket()->toArray();  

            $result = Db::table('U_cpb_fp')->insert($data[0]);

            Db::table('U_cpb_fp')->where('U_cpb_fp.cpbh', $data[0]['cpbh'])

                 ->update(['tgpy' => 'zyq']);

            Db::table('U_cpb')->delete($data[0]['cpbh']);

        });
        return $result;
    }

    /**
     * 查询废票列表的废票
     * @Author zyq
     * DateTime 2019-11-28T10:35:20+0800
     * @return [type] [description]
     */
    public function getScrticketList(){

        $data='sp30';

        $result=Db::table('U_cpb_fp')->where('U_cpb_fp.spy',$data)

            ->field('U_cpb_fp.mdcz,U_cpb_fp.rqsj,U_cpb_fp.spy,U_cpb_fp.cpbh,U_cpb_fp.zwh,pj+tbpj as pj')

            ->order('rqsj', 'desc')

            ->select();

        return $result;
    }

    /**
     * 查询售票员所对应的票号
     */

    public function TicketNum(){

        $data='sp30';

        $list=Db::table('U_yhb')->where('U_yhb.yhbh',$data)

            ->field('qsph,zzph')

            ->select();

        return json($list);

    }



}
